package edu.udel.mboch.towerdefense;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class TowerDefenseDatabase
{
	public static final String DATABASE_NAME = "TowerDefenseRedux";
	public static final String TABLE_NAME = "GameRecords";
	private SQLiteDatabase database;
	
	public TowerDefenseDatabase(Context context)
	{
		database = context.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		createGameRecordsTable();
	}
	
	public void close()
	{
		database.close();
	}
	
	private void createGameRecordsTable()
	{
        database.execSQL("CREATE TABLE IF NOT EXISTS "
                        + TABLE_NAME
                        + " (Player TEXT,"
                        + " Wave INTEGER,"
                        + " Cash INTEGER,"
                        + " Lives INTEGER, Date INTEGER);");
    }
	
    public void deleteGameRecords()
    {
        database.execSQL("DELETE FROM " + TABLE_NAME);
    }
    
    public void insertGameRecord(TowerDefenseGameRecord record)
    {
    	database.execSQL("INSERT INTO "
    					+ TABLE_NAME
    					+ " (Player,  Wave, Cash, Lives, Date)"
    					+ " VALUES ('" + record.getPlayer()
    					+ "', " + record.getWave()
    					+ ", " + record.getCash()
    					+ ", " + record.getLives()
    					+ ", " + record.getDate() + ")");
    }
    
    public List<TowerDefenseGameRecord> selectGameRecords()
    {
    	String query = "SELECT Player, Wave, Cash, Lives, Date" +
    					" FROM " + TABLE_NAME;
    	Cursor cursor = database.rawQuery(query, null);
    	try
    	{
    		int player = cursor.getColumnIndex("Player");
    		int wave = cursor.getColumnIndex("Wave");
    		int cash = cursor.getColumnIndex("Cash");
    		int lives = cursor.getColumnIndex("Lives");
    		int date = cursor.getColumnIndex("Date");
    		
    		List<TowerDefenseGameRecord> records = new ArrayList<TowerDefenseGameRecord>();
    		if(cursor.moveToFirst())
    		{
    			do
    			{
    				TowerDefenseGameRecord record = new TowerDefenseGameRecord(
    												cursor.getString(player),
    												cursor.getInt(wave),
    												cursor.getInt(cash),
    												cursor.getInt(lives),
    												cursor.getLong(date));
    				records.add(record);
    			}
    			while(cursor.moveToNext());
    		}
    		Collections.sort(records);
    		return records;
    	}
    	finally
    	{
    		cursor.close();
    	}
    }
}
